import logging
import tkinter as tk
from tkinter import scrolledtext


class LogTab:

    def __init__(self, base):
        self.base = base

    def setup_log_tab(self, parent):
        """设置日志查看界面"""
        log_text = scrolledtext.ScrolledText(parent, height=20)
        log_text.pack(fill='both', expand=True, padx=5, pady=5)

        # 日志重定向到文本框
        class TextHandler(logging.Handler):
            def __init__(self, text):
                super().__init__()
                self.text = text

            def emit(self, record):
                msg = self.format(record)
                self.text.insert(tk.END, msg + '\n')
                self.text.see(tk.END)

        log_handler = TextHandler(log_text)
        log_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(log_handler)